<?php

namespace app\api\controller\app;

use app\admin\model\Banner;
use app\admin\model\City;
use app\admin\model\Org;
use app\admin\model\OrgIndexNotice;
use app\admin\model\OrgNotice;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopdevice;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Tableyue;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\admin\model\Yueorder;
use app\api\service\DeviceService;
use app\api\service\MtService;
use app\api\service\MtUtil;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 */
class Yue extends Api
{
    protected $noNeedLogin = ['getList','sxfOrderCallback'];
    protected $noNeedRight = '*';
    protected $app;
    public function _initialize()
    {
        parent::_initialize();
        $orgModel = new Org();
        $org = $orgModel->where('id',27)->find();
        if(!$org) $this->error("该号没开通,请联系技术");
        $config = [
            'app_id' => $org['app_id'],
            'secret' => $org['app_secret'],
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
            ],
        ];
        $this->app = Factory::miniProgram($config);
    }

    public function getList()
    {
        $page = $this->request->param('page');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $keyword = $this->request->param('keyword');
        $tableYueModel = new Tableyue();
        $limit = 10;
        $offset = ($page - 1) * $limit;


        $where = "";
        $keyword = trim($keyword);
        if($keyword != ""){
             $where = " and shop_name like '%".$keyword."%'";
        }

        $sql = "select * from(
SELECT *,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_table_yue where `status` ='payed' $where) as tmp_table_name
order by distance LIMIT $offset ,$limit";

        error_log("=yue=sql==".$sql);

        $list = $tableYueModel->query($sql);

        $userModel = new \app\admin\model\User();
        foreach ($list as $key=>$val){
            $list[$key]['start_time_txt'] = date("Y-m-d H:i",$val['start_time']);
            $list[$key]['distance'] = round($val['distance']/1000,2)."km";

            $user = $userModel->where('id',$val['user_id'])->find();
            $list[$key]['avatar'] = cdnurl($user['avatar'],true);
        }

        $this->success('',$list);
    }

    public function add()
    {
        $user = $this->auth->getUser();
        $shop_id = $this->request->param('shop_id');
        $name = $this->request->param('name');
        $type = $this->request->param('type');//AA付款
        $table_type = $this->request->param('table_type');//
        $start_time = $this->request->param('start_time');//
        $mark = $this->request->param('mark');//
        $level = $this->request->param('level');



        $shopModel = new Shop();
        $shop = $shopModel->where('id',$shop_id)->find();

        $db = array();
        $db['name']= $name;
        $db['shop_id']= $shop['id'];
        $db['shop_name']= $shop['name'];
        $db['lat'] = $shop['lat'];
        $db['lng'] = $shop['lng'];
        $db['create_time'] = time();
        $db['user_id'] = $user['id'];
        $db['type'] = $type;
        $db['table_type'] = $table_type;
        $db['level'] = $level;
        $db['mark'] = $mark;
        $db['start_time'] = strtotime($start_time);


        $amount = 5;
        $tableYueModel = new Tableyue();
        $id = $tableYueModel->insertGetId($db);
        if($id){


            $order_no = getOrderSn();
            $orderDb = array();
            $orderDb['user_id'] = $user['id'];
            $orderDb['amount'] = $amount;
            $orderDb['order_no'] = $order_no;
            $orderDb['yue_id'] = $id;
            $orderDb['status'] = 'paying';
            $orderDb['create_time'] = time();

            $yueOrderModel = new Yueorder();
            $yueOrderModel->insert($orderDb);


            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/yue/sxfOrderCallback";

            $userWxModel = new Userweixin();
            $wx = $userWxModel->where('user_id',$user['id'])->find();

            $orgModel = new Org();
            $org = $orgModel->where('id', 27)->find();
            $req['mno'] = $org['mno'];//纷享未来药房
            $req['ordNo'] = $order_no;
            $req['amt'] = formatMoney($orderDb['amount']);

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = $org['app_id'];
            $req['userId'] = $wx['openid'];

            $req['subject'] = "台球约球预定金";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;


            $info = array();
            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $order_no;
                $info['payInfo'] = $result['respData'];
                $this->success('',$info);
            } else {
                $this->error($bizMsg);
            }

        }else{
            $this->error("发起失败");
        }


    }


    public function sxfOrderCallback()
    {

        $param = file_get_contents("php://input");

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);

            $yueOrderModel = new Yueorder();
            $order = $yueOrderModel->where('order_no',$out_trade_no)->find();
            $yueOrderModel->where('id',$order['id'])->update(['status'=>'payed']);
            $tableYueModel = new Tableyue();

            $tableYue = $tableYueModel->where('id',$order['yue_id'])->find();
            if($tableYue){
                $tableYueModel->where('id',$tableYue['id'])->update(['status'=>'payed']);
            }
            $count = $yueOrderModel->where('yue_id',$order['yue_id'])->count('id');
            if($count == 2){
                $tableYueModel->where('id',$tableYue['id'])->update(['status'=>'wait']);


                $userModel = new \app\admin\model\User();
                $user = $userModel->where('id',$tableYue['click_user_id'])->find();

                $userWxModel = new Userweixin();
                $wx = $userWxModel->where('user_id',$tableYue['user_id'])->find();
                $data = [
                    'template_id' => 'PKGHDClIKC1gIowLVzy9wi_POF1sT8kz9WNM5sP1NSw', // 所需下发的订阅模板id
                    'touser' => $wx['openid'],     // 接收者（用户）的 openid
                    'page' => 'pages/home/index2',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                        'thing3' => [
                            'value' => $tableYue['name'],
                        ],
                        'thing2' => [
                            'value' => $tableYue['shop_name'],
                        ],
                        'date6' => [
                            'value' => date("Y-m-d H:i",$tableYue['start_time']),
                        ],
                        'thing9' => [
                            'value' => $user['name'],
                        ],
                        'phone_number13' => [
                            'value' => $user['mobile'],
                        ],
                    ],
                ];

                $ret = $this->app->subscribe_message->send($data);
            }




        }

    }

    public function join()
    {

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $tableYueModel = new Tableyue();
        $table = $tableYueModel->where('id',$id)->find();
        if($table['status'] != 'payed'){
            $this->error("此约球已有人");
        }
        if($table['user_id'] == $user['id']){
            $this->error("不能约自己发布的活动");
        }
        $tableYueModel->where('id',$id)->update(['click_user_id'=>$user['id']]);


        $amount = 5;
        $order_no = getOrderSn();
        $orderDb = array();
        $orderDb['user_id'] = $user['id'];
        $orderDb['amount'] = $amount;
        $orderDb['order_no'] = $order_no;
        $orderDb['yue_id'] = $id;
        $orderDb['status'] = 'paying';
        $orderDb['create_time'] = time();

        $yueOrderModel = new Yueorder();
        $yueOrderModel->insert($orderDb);


        $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/yue/sxfOrderCallback";

        $userWxModel = new Userweixin();
        $wx = $userWxModel->where('user_id',$user['id'])->find();

        $orgModel = new Org();
        $org = $orgModel->where('id', 27)->find();
        $req['mno'] = $org['mno'];//纷享未来药房
        $req['ordNo'] = $order_no;
        $req['amt'] = formatMoney($orderDb['amount']);

        $req['payType'] = "WECHAT";
        $req['payWay'] = "03";
        $req['subAppid'] = $org['app_id'];
        $req['userId'] = $wx['openid'];

        $req['subject'] = "台球约球应约金";
        $req['tradeSource'] = "01";
        $req['trmIp'] = get_client_ip();
        $req['notifyUrl'] = $url;


        $info = array();
        $vbillService = new VbillService();
        $res = $vbillService->jsApi($req);
        $result = json_decode($res, true);
        $bizCode = $result['respData']['bizCode'];
        $bizMsg = $result['respData']['bizMsg'];

        if ($bizCode == '0000') {
            $info['order_no'] = $order_no;
            $info['payInfo'] = $result['respData'];
            $this->success('',$info);
        } else {
            $this->error($bizMsg);
        }

        $this->success('');
    }


    public function joinList()
    {

        $page = $this->request->param('page');
        $status = $this->request->param('status');
        $user = $this->auth->getUser();

        $user_id = $user['id'];
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = array();
        if($status != ''){
            $where['Tableyue.status'] = $status;
        }
        $yueModel = new Tableyue();
        $userModel = new \app\admin\model\User();
        $list = $yueModel->where('order.status','in',['payed','refund'])->where($where)->where('order.user_id',$user['id'])->with(['order'])->limit($offset,$limit)->select();
        foreach ($list as $key=>$val){
            $list[$key]['start_time_txt'] = date("Y-m-d H:i",$val['start_time']);

            $user = $userModel->where('id',$val['user_id'])->find();
            $clickUser = $userModel->where('id',$val['click_user_id'])->find();

            $list[$key]['avatar'] = cdnurl($user['avatar'],true);
            if($clickUser){
                $list[$key]['avatar2'] =cdnurl($clickUser['avatar'],true);
            }else{
                $list[$key]['avatar2'] = "";
            }

            if($val['status'] == 'payed'){
                $list[$key]['status'] = "待应约";
            }else if($val['status'] == 'wait'){
                $list[$key]['status'] = "待开局";
            }else if($val['status'] == 'doing'){
                $list[$key]['status'] = "进行中";
            }else if($val['status'] == 'done'){
                $list[$key]['status'] = "已完成";
            }else if($val['status'] == 'cancel'){
                $list[$key]['status'] = "已取消";
            }
            if($user_id == $user['id']){
                if($clickUser){
                    $list[$key]['tel'] = $clickUser['mobile'];
                }else{
                    $list[$key]['tel'] ="";
                }

            }else{
                $list[$key]['tel'] = $user['mobile'];
            }

        }

        $this->success('',$list);

    }

    public function cancel()
    {
        $user = $this->auth->getUser();
        $id = $this->request->param('id');


        //1. 离开台时间 在2个小时内，取消约球 属于爽约
        //2. 超过24小时未 开台，约球自动取消，属于爽约
        //3. 未约球成功 ，主动取消或者自动取消 不属于爽约

        $tableYueModel = new Tableyue();
        $yueOrderModel = new Yueorder();
        $table = $tableYueModel->where('id',$id)->find();
        if($table['status'] =='done' || $table['status'] =='doing'){
            $this->error("此订单状态不可取消");
        }
        $orgModel = new Org();
        $org = $orgModel->where('id', 27)->find();
        if($table['status'] =='payed'){

            //退款
            $yueOrder = $yueOrderModel->where('yue_id',$table['id'])->where('user_id',$table['user_id'])->find();
            if($yueOrder){

                $refundOrder_no = getOrderSn();

                $orgModel = new Org();
                $org = $orgModel->where('id', 27)->find();
                $req = array();
                $req['mno'] = $org['mno'];
                $req['ordNo'] = $refundOrder_no;
                $req['origOrderNo'] = $yueOrder['order_no'];
                $req['amt'] = $yueOrder['amount'];

                $vbillService = new VbillService();
                $ret = $vbillService->refund($req);

                $result = json_decode($ret, true);
                if ($result['respData']['bizCode'] != "0000") {
                    $this->error($result['respData']['bizMsg']);
                }

                $yueOrderModel->where('id',$yueOrder['id'])->update(['status'=>'refund']);
                $tableYueModel->where('id',$id)->update(['status'=>'cancel']);

                $this->success('成功');
            }else{
                $this->error("订单不存在,无法发起取消");
            }
        }else if($table['status'] =='wait'){
            //
            $startTime = $table['start_time'];
            $differenceInHours = abs($startTime - time()) / 3600;
            $hour = $differenceInHours;

            if($hour <=2 && $hour >0){
                //爽约  把钱给 另外一个用户
                $userAllBalanceModel = new Userallbalance();
                $yueOrder = $yueOrderModel->where('yue_id',$table['id'])->where('user_id',$user['id'])->find();

                $tempUserId = $user['id'];
                if($tempUserId == $table['user_id']){
                    $tempUserId = $table['click_user_id'];
                }else{
                    $tempUserId = $table['user_id'];
                }

                $db = array();
                $db['user_id'] = $tempUserId;
                $db['type'] = "in";
                $db['amount'] = $yueOrder['amount'];
                $db['create_time'] =time();
                $db['from'] = "yue";
                $db['order_id'] = $table['id'];
                $db['shop_profit'] = 0;
                $db['order_type'] = "tq";
                $db['ratio'] = 1;
                $userAllBalanceModel->insert($db);

                $yueOrder = $yueOrderModel->where('user_id',$tempUserId)->where('yue_id',$table['id'])->select();
                $req = array();
                $req['mno'] = $org['mno'];
                $req['ordNo'] = getOrderSn();
                $req['origOrderNo'] = $yueOrder['order_no'];
                $req['amt'] = $yueOrder['amount'];

                $vbillService = new VbillService();
                $ret = $vbillService->refund($req);

                $result = json_decode($ret, true);
                if ($result['respData']['bizCode'] != "0000") {
                    $this->error($result['respData']['bizMsg']);
                }
                $yueOrderModel->where('id',$yueOrder['id'])->update(['status'=>'refund']);
                $tableYueModel->where('id',$id)->update(['status'=>'cancel']);

                $this->success('成功');
            }else if($hour >2){
                //退款 双方
                $orderList = $yueOrderModel->where('yue_id',$table['id'])->select();

                foreach ($orderList as $key=>$val){

                    $req = array();
                    $req['mno'] = $org['mno'];
                    $req['ordNo'] = getOrderSn();
                    $req['origOrderNo'] = $val['order_no'];
                    $req['amt'] = $val['amount'];

                    $vbillService = new VbillService();
                    $ret = $vbillService->refund($req);

                    $result = json_decode($ret, true);
                    if ($result['respData']['bizCode'] != "0000") {
                        $this->error($result['respData']['bizMsg']);
                    }
                    $yueOrderModel->where('id',$val['id'])->update(['status'=>'refund']);

                }
                $tableYueModel->where('id',$id)->update(['status'=>'cancel']);


                $this->success('成功');
            }

        }


    }

}
